package com.bjsxt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bjsxt.constants.Constants;
import com.bjsxt.domain.User;
import com.bjsxt.dto.UserDto;
import com.bjsxt.mapper.RoleMapper;
import com.bjsxt.mapper.UserMapper;
import com.bjsxt.service.UserService;
import com.bjsxt.utils.AppMd5Utils;
import com.bjsxt.vo.DataGridView;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @author Administrator
 * @title: UserServiceImpl
 * @projectName open-his
 * @description: TODO
 * @date 2020/12/29 0029
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 根据手机号查询用户
     *
     * @param phone
     * @return
     */
    @Override
    public User queryUserByPhone(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(User.COL_PHONE, phone);
        User user = this.userMapper.selectOne(queryWrapper);
        return user;
    }

    /**
     * 根据id查询用户
     *
     * @param userId
     * @return
     */
    @Override
    public User getOne(Long userId) {
        return this.userMapper.selectById(userId);
    }

    /**
     * 分页查询用户
     *
     * @param userDto
     * @return
     */
    @Override
    public DataGridView listUserForPage(UserDto userDto) {
        Page<User> page = new Page<>(userDto.getPageNum(), userDto.getPageSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(userDto.getUserName()), User.COL_USER_NAME, userDto.getUserName());
        queryWrapper.like(StringUtils.isNotBlank(userDto.getPhone()), User.COL_PHONE, userDto.getPhone());
        queryWrapper.eq(StringUtils.isNotBlank(userDto.getStatus()), User.COL_STATUS, userDto.getStatus());
        queryWrapper.eq(userDto.getDeptId() != null, User.COL_DEPT_ID, userDto.getDeptId());
        queryWrapper.ge(null != userDto.getBeginTime(), User.COL_CREATE_TIME, userDto.getBeginTime());
        queryWrapper.le(null != userDto.getEndTime(), User.COL_CREATE_TIME, userDto.getEndTime());
        queryWrapper.orderByAsc(User.COL_USER_ID);
        this.userMapper.selectPage(page, queryWrapper);
        return new DataGridView(page.getTotal(), page.getRecords());
    }

    /**
     * 添加用户
     *
     * @param userDto
     * @return
     */
    @Override
    public int addUser(UserDto userDto) {
        User user = new User();
        BeanUtil.copyProperties(userDto, user);
        user.setUserType(Constants.USER_NORMAL);
        String defaultPwd = user.getPhone().substring(5);
        user.setCreateBy(userDto.getSimpleUser().getUserName());
        user.setCreateTime(DateUtil.date());
        user.setSalt(AppMd5Utils.createSalt());
        user.setPassword(AppMd5Utils.md5(defaultPwd, user.getSalt(), 2));
        return this.userMapper.insert(user);
    }

    /**
     * 修改用户
     *
     * @param userDto
     * @return
     */
    @Override
    public int updateUser(UserDto userDto) {
        User user = this.userMapper.selectById(userDto.getUserId());
        if (null == user) {
            return 0;
        }
        BeanUtil.copyProperties(userDto, user);
        user.setUpdateBy(userDto.getSimpleUser().getUserName());
        return this.userMapper.updateById(user);
    }

    /**
     * 根据id删除用户
     *
     * @param userIds
     * @return
     */
    @Override
    public int deleteUserByIds(Long[] userIds) {
        List<Long> ids = Arrays.asList(userIds);
//        根据用户ids删除sys_role_user中间表里面的数据
        this.roleMapper.deleteRoleUserByUserIds(ids);
        return this.userMapper.deleteBatchIds(ids);
    }

    /**
     * 查询所有可用的用户
     *
     * @return
     */
    @Override
    public List<User> getAllUsers() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(User.COL_STATUS, Constants.STATUS_TRUE);
        queryWrapper.eq(User.COL_USER_TYPE, Constants.USER_NORMAL);
        queryWrapper.orderByDesc(User.COL_USER_ID);
        return this.userMapper.selectList(queryWrapper);
    }

    /**
     * 重置用户密码【判断用户是否为管理员，并设置初始密码，管理员：123456，普通用户：手机号去掉前五位】
     *
     * @param userIds
     */
    @Override
    public void resetPassWord(Long[] userIds) {
        for (Long userId : userIds) {
            User user = this.userMapper.selectById(userId);
            String defaultPwd = "";
            if (user.getUserType().equals(Constants.USER_ADMIN)) {
                defaultPwd = "123456";
            } else {
                defaultPwd = user.getPhone().substring(5);
            }
            user.setSalt(AppMd5Utils.createSalt());
            user.setPassword(AppMd5Utils.md5(defaultPwd, user.getSalt(), 2));
            this.userMapper.updateById(user);
        }
    }

    /**
     * 查询所有需要排班的医生
     *
     * @param userId
     * @param deptId
     * @return
     */
    @Override
    public List<User> queryUsersNeedScheduling(Long userId, Long deptId) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(null != userId, User.COL_USER_ID, userId);
        queryWrapper.eq(null != deptId, User.COL_DEPT_ID, deptId);
        queryWrapper.eq(User.COL_SCHEDULING_FLAG, Constants.SCHEDULING_FLAG_TRUE);
        return this.userMapper.selectList(queryWrapper);
    }
}
